<?php
namespace app\controllers;

use Yii;
use app\common\widgets\Tools;
use app\models\AdminModel;
use app\models\User;
use app\models\dao\Admin;
use app\models\dao\Role;
use yii\data\Pagination;

/**
 * User controller
 */
class UserController extends BaseController {

	public $admin;
	public $defaultAction = 'lists';

	public function init() {
		parent::init();
		$this->admin = new AdminModel();
	}

	public function actionIndex() {
		return $this->redirect(\Yii::$app->urlManager->createUrl(['user/lists']));
	}

	public function actionLists() {
		$ary_page_data = [];
		$filter = [];
		$page = \Yii::$app->request->get('page',1);
		$keyword = \Yii::$app->request->get('keyword');
		$state = \Yii::$app->request->post('state');
		$page_params = [
			'pageno'=> $page,
			'pagesize'=> $this->_limit,
		];
		$filter['page'] = $page;
		$query = [];
		$filter['keyword'] = '';
		if(!empty($keyword)) {
			$query = [
				'where'=>['name'=>$keyword],
			];
			$filter['keyword'] = $keyword;
		}
		if($state > 0 ) {
			$query['where']['role_id'] = $state;
			$filter['state'] = $state;
		}
		$ary_data = $this->admin->getAll($query, $page_params);

		$where = array(
			'status'   => 1,
			'flag'  => 1
		);
		$ary_role = Role::find()->where($where)->asArray()->all();

		$pagination = new Pagination([
				'defaultPageSize' => $this->_limit,
				'totalCount' => $ary_data['total_results'],
		]);
		$ary_page_data['pages'] = $pagination;

		$ary_page_data['role'] = $ary_role;

//        echo "<pre>";print_r($ary_data);exit;
		$ary_page_data['data'] = $ary_data['datalist'];
		$ary_page_data['total'] = $ary_data['total_results'];
		$ary_page_data['limit'] = $this->_limit;
		$ary_page_data['filter'] = $filter;
		return $this->render('lists', $ary_page_data);
	}

	//修改密码
	public function actionPasswd() {
		$ary_page_data = array();
		$int_id = \Yii::$app->user->getId();
		$ary_page_data['id'] = $int_id;
		return $this->render('passwd', $ary_page_data);
	}

	public function actionAdd() {
		$ary_page_data = [];
		$where = array(
			'status'   => 1,
			'flag'  => 1,
			'type' => $this->userType,
		);
		$ary_role = Role::find()->where($where)->asArray()->all();
		$ary_page_data['role'] = $ary_role;
		return $this->render('add', $ary_page_data);
	}

	public function actionDoadd() {
		$name = \Yii::$app->request->post('username');
		$role_id = (int)\Yii::$app->request->post('role_id', 0);
		$username = \Yii::$app->request->post('nick');
		$status = (int)\Yii::$app->request->post('status', 0);
		$passwd = \Yii::$app->request->post('password');
		$confirm_passwd = \Yii::$app->request->post('confirm_passwd');

		if(empty($name)) {
			Tools::sendJson(40000202, "用户名不能为空，请重新输入");
		}

		if($role_id <= 0) {
			Tools::sendJson(40000203, "请选择对应权限");
		}

		if(empty($passwd) || empty($confirm_passwd)) {
			Tools::sendJson(40000204, "请密码、确认密码填写完整");
		}

		if(md5($confirm_passwd) != md5($passwd)) {
			Tools::sendJson(40000205, "两次密码输入不同，请重新输入");
		}

		$data = array(
			'username'  => $name,
			'password'  => md5($passwd),
			'role_id'  => $role_id,
			'nick'  => $username,
			'status'    => $status,
			'create_time' => date("Y-m-d H:i:s"),
			'ip'  => Tools::getClientIP(),
		);
		$ary_result = $this->admin->create($data);
		if(true === $ary_result['status']) {
			Tools::sendJson(0, "添加成功", \Yii::$app->urlManager->createUrl(['user/lists']));
		} else {
			Tools::sendJson(40000206, "添加失败");
		}
	}

	public function actionCheckname() {
		$ary_get = \Yii::$app->request->get();
		if(!empty($ary_get['username']) && isset($ary_get['username'])){
			if(!empty($ary_get['id']) && isset($ary_get['id'])){
				$where = array(
					'username'    => $ary_get['username'],
					'id'  => $ary_get['id']
				);
				$ary_result = $this->admin->CheckName($where);
				if(TRUE === $ary_result){
					$this->ajaxReturn("该帐号已存在");
				}else{
					$this->ajaxReturn(true);
				}
			}else{
				$params = array(
					'username'  => $ary_get['username']
				);
				$ary_result = $this->admin->CheckName($params);

				if(TRUE === $ary_result){
					$this->ajaxReturn("该用户名已存在");
				}else{
					$this->ajaxReturn(true);
				}

			}
		}else{
			$this->ajaxReturn("用户名不能为空");
		}
	}

	/**
	 * @return mixed
	 */
	public function actionProfile() {
		//个人资料
		$ary_page_data = array();
		$int_id = \Yii::$app->user->getId();
		$where = array(
			'id'   => $int_id
		);
		$ary_user = User::find()->with("role")->where($where)->one();

		$ary_page_data['data'] = $ary_user;
		return $this->render('profile', $ary_page_data);
	}

	public function actionModifypwd() {
		$ary_post = $this->_post();

		if(!empty($ary_post)) {
			$password = trim($this->_post('password'));
			$comfirmpasswd = trim($this->_post('comfirmpasswd'));
			if(empty($ary_post['oldpass']) && !isset($ary_post['oldpass'])) {
				Tools::sendJson(80000101, "原密码不能为空");
			}

			if(empty($password)) {
				Tools::sendJson(80000102, "新密码不能为空");
			}
			if(empty($comfirmpasswd)) {
				Tools::sendJson(80000103, "确认密码密码不能为空");
			}
			if(md5($password) != md5($comfirmpasswd)) {
				Tools::sendJson(80000104, "两次输入不同，请重新输入");
			}
			$int_id = (int)\Yii::$app->user->getId();
			$ary_user = User::find()->where(array('id'=> $int_id))->one();
			if(!empty($ary_user)) {
				if(md5($ary_post['oldpass']) != $ary_user['password']) {
					Tools::sendJson(80000105, "原密码错误，请重新输入");
				}

				$data = array(
					'password'  => md5($password)
				);
				$userObj = new User();
				$update_user = $userObj->updateAll($data, 'id = :id',
					[':id'=>$int_id]);
				if ($update_user >= 0) {
					self::Log("更新密码成功");
					Tools::sendJson(0, "更新密码成功", \Yii::$app->urlManager->createUrl(['site/logout']));
				} else {
					Tools::sendJson(80000106, "更新密码失败");
				}
			} else {
				Tools::sendJson(80000107, "该管理员不存在");
			}
		} else {
			Tools::sendJson(80000108, "参数错误");
		}
	}

	public function actionEdit() {
		$ary_page_data = array();
		$int_id = (int)\Yii::$app->request->get('id');
		if(empty($int_id)) {
			Tools::sendJson(40000301, "非法操作，请重试");
		}
		$ary_data = $this->admin->getOne($int_id);
		if(empty($ary_data)) {
			Tools::sendJson(40000302, "该帐号不存在或已删除!");
		}
		$where = array(
			'status'   => 1,
			'flag'	=> 1,
			'type' => $this->userType,
		);
		$ary_role = Role::find()->where($where)->all();
		$ary_page_data['role'] = $ary_role;
		$ary_page_data['data'] = $ary_data;
		return $this->render('edit', $ary_page_data);
	}

	public function actionEditsave() {
		$id = (int)\Yii::$app->request->post('id', 0);
		$name = \Yii::$app->request->post('username');
		$role_id = (int)\Yii::$app->request->post('role_id', 0);
		$username = \Yii::$app->request->post('nick');
		$status = (int)\Yii::$app->request->post('status', 0);
		$passwd = \Yii::$app->request->post('password');
		$confirm_passwd = \Yii::$app->request->post('confirm_passwd');

		if(empty($name)) {
			Tools::sendJson(40000202, "用户名不能为空，请重新输入");
		}

		if($role_id <= 0) {
			Tools::sendJson(40000203, "请选择对应权限");
		}
		$data = [
			'id' => $id,
			'username'  => $name,
			'role_id'  => $role_id,
			'nick'  => $username,
			'status'    => $status,
			'create_time' => date("Y-m-d H:i:s"),
			'ip'  => Tools::getClientIP(),
		];
		if(!empty($passwd) && !empty($confirm_passwd)) {
			if(md5($confirm_passwd) != md5($passwd)) {
				Tools::sendJson(40000205, "两次密码输入不同，请重新输入");
			}
			$data['password'] = md5($passwd);
		}
		$ary_result = $this->admin->modify($data);
		if(true === $ary_result) {
			Tools::sendJson(0, "更新成功", \Yii::$app->urlManager->createUrl(['user/lists']));
		} else {
			Tools::sendJson(40000206, "更新失败");
		}
	}

	public function actionEditrole() {
		$ary_page_data = array();
		return $this->render('edit_role', $ary_page_data);
	}

	public function actionModifyuserrole() {

	}

	/**
	 * 删除管理员
	 */
	public function actionDodel(){
		$ary_post = $this->_post();
		if(!empty($ary_post['id']) && isset($ary_post['id'])){
			$int_id = intval($ary_post['id']);
			$where = array(
				'id'   => $int_id,
				'flag'  => 1
			);
			$ary_user = User::find()->where($where)->one();
			if(empty($ary_user)) {
				Tools::sendJson("40000109", "该管理员不存在或已删除");
			}
			if($ary_user['username'] == 'admin') {
				Tools::sendJson("40000110", "该账户为系统管理员不允许删除!");
			}
			$data = array(
				'id'    => $int_id,
				'flag'  => 0,
			);
			$ary_result = $this->admin->modify($data);
			if(FALSE === $ary_result){
				Tools::sendJson("40000111", "删除失败");
			}  else {
				Tools::sendJson("0", "删除成功", \Yii::$app->urlManager->createUrl(['user/lists']));
			}
		}else{
			Tools::sendJson("40000108", "该管理员不存在");
		}
	}
}